<?php
namespace app\cgi\controller;

use app\lib\WxUser;
use app\lib\WxApp;

class Connect extends Base{
    public function openid(){
        $id = (string)$this->request->post('req_id');
        $iv = $this->request->post('iv/s','');
        !$id && $this->responseError('参数错误');
        $app = new WxApp($this->ty_id);
        $back = $app->wx->getWxOpenId($id);
        if( isset($back['errcode']) ) {
            $this->responseError($back['errmsg']);
        }
        if( parent::hasCache('User_'.$back['openid']) ) {
            $userInfo = parent::getCache('User_'.$back['openid']);
        } else {
            $u = new WxUser($this->ty_id);
            $u->initIv($iv,'id');
            if( !$u->setUserInfo([
                'openid'=>$back['openid'],
                'nickname'=>'',
                'headimgurl'=>'',
                'city'=>'',
                'create_time'=>time(),
            ]) ) {
                $this->responseError($u->err_msg);
            }
            $userInfo = $u->userInfo;
            parent::setCache('User_'.$userInfo['openid'],$userInfo);
        }
        $this->response('',['wx'=>$back,'user'=>$userInfo]);
    }
    /*微信登录*/
    public function auth(){
        $data = $this->request->post();
        ( !isset($data['openid']) || !isset($data['nickName']) || !isset($data['avatarUrl']) ) && $this->responseError(1001,'参数错误');
        ( '' === $data['openid'] ) && $this->responseError('openid为空');
        'https://wx.qlogo.cn' == substr($data['avatarUrl'],0,19) && $data['avatarUrl'] = downExternalUrlImg($data['avatarUrl']);
        $u = new WxUser($this->ty_id);
        $u->initIv(isset($data['iv'])?$data['iv']:'','id');
        if( !$u->setUserInfo([
            'openid'=>$data['openid'],
            'nickname'=>$data['nickName'],
            'headimgurl'=>$data['avatarUrl'],
            'city'=>isset($data['city'])?$data['city']:'',
            'ctime'=>time(),
        ]) ) {
            $this->responseError($u->err_msg);
        }
        parent::setCache('User_'.$u->userInfo['openid'],$u->userInfo);
        $this->response('',$u->userInfo);
    }
}
